import {Table, message} from 'antd'
import {get} from '../utils/http'
import React from 'react'
import PropTypes from 'prop-types';

export default class RemoteTable extends React.Component{
    constructor(props){
        super(props)
        this.handleTableChange = this.handleTableChange.bind(this)
    }
    static propTypes = {
        url: PropTypes.string,
        dataProxy: PropTypes.func,
        extend: PropTypes.object,//分页条件
    }
    state = {
        data: [],
        pagination: {},
        loading: false
    }
    handleTableChange(pagination, filters, sorter) {
        const pager = {...this.state.pagination}
        pager.current = pagination.current
        this.setState({
            pagination:pager
        })
        this.fetch({
            page: pagination.current,
            ...filters,
            ...this.props.extend
        })
    }
    componentDidMount() {
        this.fetch()
    }
    refresh() {
        const pager = { ...this.state.pagination }
        pager.current = 1
        this.setState({
            pagination: pager
        });
        this.fetch({
            page: pager.current,
            ...this.props.extend,
        });
    }
    async fetch(params = {}){
        this.setState({loadiing:true})
        let {url, dataProxy} = this.props
        try{
            let result = await get(url, params)
            let { pagination, data } = dataProxy(result);
            console.log('pagination==>', pagination, data);
            this.setState({
                loading:false,
                data: data,
                pagination,
            });
        }catch(err) {
            console.error('err==>', err)
            if(err.type === 1){
                message.error(err.error)
            }
        }
    }
    render() {
        return <Table
            pagination={this.state.pagination}
            dataSource={this.state.data}
            loading={this.state.loading}
            onChange={this.handleTableChange}
        >
            {this.props.children}
        </Table>
    }
}
